package com.autonavi.abs.generator.core.generator.mapper;

import com.autonavi.abs.generator.common.enumeration.TemplateEnum;
import com.autonavi.abs.generator.common.model.ColumnMeta;
import com.autonavi.abs.generator.common.model.TableMeta;
import com.autonavi.abs.generator.core.generator.AbstractGenerator;
import com.autonavi.abs.generator.util.GenerateUtil;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @author tianquan.ld
 * @version V1.0
 * <p>Description: mapper生成器</p>
 * @date 2020-08-10 17:25
 */
@Slf4j
@Component
public class MapperGenerator extends AbstractGenerator {

    private TemplateEnum templateType = TemplateEnum.Mapper;

    @Override
    public TemplateEnum getTemplateTypeEnum() {
        return templateType;
    }

    @Override
    public String getTemplateType() {
        return templateType.name();
    }

    @Override
    public void generate(TableMeta tableMeta) {

        try {

            List<ColumnMeta> columnMetaList = sourceCenterService.getColumnMetaList(tableMeta.getName());

            Map<String, Object> dataMap = Maps.newHashMap();
            dataMap.put("appProperty", app);
            dataMap.put("tableMeta", tableMeta);
            dataMap.put("columnList", columnMetaList);
            dataMap.put("columnNames",getColumnNamesStr(columnMetaList));

            GenerateUtil.generateModule(freeMarkerConfigurer, templateType, dataMap);
        } catch (Exception e) {
            log.info("生成失败:{}", templateType.name());
            log.error(e.getMessage(), e);
        }
    }

    private String getColumnNamesStr(List<ColumnMeta> columnList) {

        StringBuilder builder = new StringBuilder();
        if (CollectionUtils.isEmpty(columnList)) {
            return "";
        } else {
            for (ColumnMeta column : columnList) {
                builder.append(column.getName()).append(",");
            }
            String result = builder.toString();
            return result.substring(0, result.length() - 1);
        }
    }

}
